package com.bw.lib_net

import com.bw.lib_net.custom.CustomGsonConverterFactory
import com.bw.lib_net.interceptor.TokenInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @Author : ZhouZiYao
 * @Time : On 2023/11/17 10:44
 * @Description :
 */
class RetrofitManager {

    companion object{
        //常量：超时事件
        const val TIMEOUT = 60L
        @JvmStatic
        val instance: RetrofitManager by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            RetrofitManager()
        }
    }

    private val retrofit: Retrofit = Retrofit.Builder()
        .baseUrl(BuildConfig.SERVER_URL)
        .client(createOkhttp())
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    private fun createOkhttp(): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(TIMEOUT,TimeUnit.HOURS)
            .writeTimeout(TIMEOUT,TimeUnit.HOURS)
            .readTimeout(TIMEOUT,TimeUnit.HOURS)
            .addInterceptor(TokenInterceptor())
            .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .build()
    }

    /**
     * 泛型函数:生成对应的Api接口对象
     */
    fun <T> createService(service: Class<T>): T {
        return retrofit.create(service)
    }

}